import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, BackHandler, FlatList, ToastAndroid } from 'react-native';

const tagData = [
  {label:'综合新闻',id:'1'},
  {label:'通知公告',id:'2'},
  {label:'媒体聚焦',id:'3'},
  {label:'教学科研',id:'4'},
  {label:'基层动态',id:'5'}
]

const B = ({children,style,...rest}) => {
  return (
    <TouchableOpacity {...rest} style={[style,{borderRadius:5,alignItems:'center',justifyContent:'center'},]}>
      <Text style={{color:style.color?style.color:'#fff'}}>{children}</Text>
    </TouchableOpacity>
  )
}

const baseURL = 'http://8.142.171.141:8080/school-news'

export default App = () => {
  const [tag,setTag] = useState('1');
  const [page,setPage] = useState(1);
  const [newsList,setNewsList] = useState([]);
  const [refreshing,setRefreshing] = useState(false);

  let time = 0;

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
		
		if(Date.now() - time > 2000) {
			time = Date.now()
			ToastAndroid.show(
				'确定退出吗？',
				ToastAndroid.SHORT
			)
		}else{
			BackHandler.exitApp()
		}

		return true
	  }
    );

    return () => backHandler.remove();
  }, []);

  useEffect(() => {
	fetch(`${baseURL}/draft/pageList?page=${page}&size=40`)
	.then(res => res.json())
	.then(res => {
		if(page == 1) {
			setNewsList(res.data.content)
		}else{
			setNewsList([...newsList,...res.data.content])
		}
		
		setRefreshing(false)
	})
  },[])

  const onEndReached = () => {
	setPage(page+1)
  }

  const onRefresh = () => {
	setPage(1)
	setRefreshing(true)
  }

  return (
    <View style={styles.layout}>
        <View style={{flexDirection:'row',justifyContent:'space-around',marginVertical:20,}}>
			{
				tagData.map(item => {
					return <B style={{width:'18%',height:20,color:'#000',backgroundColor:tag === item.id?'#f00':'#ccc'}} onPress={() => setTag(item.id)} key={item.id}>{item.label}</B>
				})
			}
        </View>
		{/*FlatList不能放在ScrollView里*/}
		<FlatList
			data={newsList}
			renderItem={({item}) => 
				<View style={{margin:10,backgroundColor:'red'}}>
					<Text ellipsizeMode='tail'>{item.draftTitle}</Text>
					<Text>{item.draftContext}</Text>
				</View>
			}
			keyExtractor={(a)=>a.id}
			onEndReached={onEndReached}
			onRefresh={onRefresh}
			refreshing={refreshing}
		></FlatList>
    </View>
  );
}

const styles = StyleSheet.create({
  layout:{
    padding:20
  }
});
